//
//  SettingTurnPeriodViewController.m
//  SIqICalendar
//
//  Created by SKiran on 17/2/28.
//  Copyright © 2017年 sjw. All rights reserved.
//
//  设置倒班页
//

#import "SettingTurnPeriodViewController.h"
#import "SettingTurnLastStepViewController.h"
#import "JWCalendarModel.h"
#import "JWScheduleModel.h"
#import "JWRealmManager.h"

#define TAG_BASE    1000
#define ALERT_VIEW_TAG_BASE 10000
@interface SettingTurnPeriodViewController ()<UITextFieldDelegate,UIAlertViewDelegate>
@property(nonatomic, strong)NSMutableArray  *selectedSchedules;
@property(nonatomic, strong)NSMutableArray  *allScheduleDatas;
@end

@implementation SettingTurnPeriodViewController
{
    UILabel              *_titleLabel;
    UIView               *_selectTurnBgView;
    UIScrollView         *_selectTurnScrollView;
    CGFloat              _selectTurnHeight;
}

- (void)viewDidLoad {
    
    [super viewDidLoad];
    
    [self initalTitleView];
    
    [self initialData];
    
    [self createView];
}

- (void)initialData {
    _selectTurnHeight = WGiveHeight(30);
}

- (void)createView {
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemReply target:self action:@selector(backout:)];
    
    UIView  *lineV = [[UIView alloc]init];
    lineV.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:lineV];
    
    CGFloat leftMargin = WGiveWidth(30.f);
    CGFloat topMargin = WGiveHeight(150.f);
    CGFloat lineVWidth = kScreenWidth - 2*leftMargin;
    [lineV makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(leftMargin);
        make.width.equalTo(lineVWidth);
        make.height.equalTo(2);
        make.top.equalTo(self.view.top).equalTo(topMargin);
    }];
    
    // 说明label
    UILabel *notesLabelInTop = [[UILabel alloc]init];
    notesLabelInTop.text = @"请点击下面的按钮设置您的排班顺序\n长按下面的班名可以修改哦~";
    notesLabelInTop.textColor = UIColorFromRGB(0xCCCCCC);
    notesLabelInTop.font = [UIFont systemFontOfSize:defaultFont];
    notesLabelInTop.textAlignment = NSTextAlignmentCenter;
    notesLabelInTop.numberOfLines = 0;
    [self.view addSubview:notesLabelInTop];
    
    [notesLabelInTop makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(0);
        make.top.equalTo(lineV.bottom).offset(WGiveHeight(10));
    }];
    
    // 8个倒班按钮
    UIView *btnsBgView = [[UIView alloc]init];
    btnsBgView.backgroundColor = [UIColor clearColor];
    [self.view addSubview:btnsBgView];
    
    CGFloat btnMargin = WGiveWidth(15);// 按钮之间的间距
    CGFloat btnWidth = (lineVWidth - 3 * btnMargin) / 4.0; // 按钮的大小
    
    [btnsBgView makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(lineV.left);
        make.width.equalTo(lineVWidth);
        make.top.equalTo(notesLabelInTop.bottom).offset(leftMargin);
        make.height.equalTo(btnWidth * 2 + btnMargin * 2);
    }];
    
    
    for (int i = 0; i < 8; i++) {
        UIButton *btn = [[UIButton alloc] initWithFrame:CGRectZero];
        btn.backgroundColor = [UIColor clearColor];
        
        btn.layer.masksToBounds = YES;
        btn.layer.cornerRadius = btnWidth/2;
        [btnsBgView addSubview:btn];
        
        JWScheduleModel *model = self.allScheduleDatas[i];
        
        [btn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        btn.titleLabel.font = [UIFont boldSystemFontOfSize:30.f];
        
        btn.tag = TAG_BASE + i;
        [btn addTarget:self action:@selector(btnBackGroundHighlighted:) forControlEvents:UIControlEventTouchDown];
        [btn addTarget:self action:@selector(btnEventTouchUpInside:) forControlEvents:UIControlEventTouchUpInside];
        
        btn.titleLabel.baselineAdjustment = UIBaselineAdjustmentAlignCenters;
        [btn setTitle:model.scheduleName forState:UIControlStateNormal];
        [btn setBackgroundColor:model.scheduleColor];
        [btn.titleLabel setAdjustsFontSizeToFitWidth:YES];
        
        UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(btnLong:)];
        longPress.minimumPressDuration = 0.8; //定义按的时间
        [btn addGestureRecognizer:longPress];
        
        [btn makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo((btnWidth + btnMargin) * (i / 4));
            make.width.equalTo(btnWidth);
            make.height.equalTo(btnWidth);
            make.leftMargin.equalTo((btnWidth + btnMargin) * (i % 4));
        }];
    }
    
    UIButton *nextStepBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [nextStepBtn setTitle:@"下一步" forState:UIControlStateNormal];
    [nextStepBtn setBackgroundColor:[UIColor clearColor]];
    nextStepBtn.titleLabel.font = [UIFont boldSystemFontOfSize:25.f];
    [nextStepBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    nextStepBtn.layer.masksToBounds = YES;
    nextStepBtn.layer.cornerRadius = 10;
    nextStepBtn.layer.borderWidth = 2;
    nextStepBtn.layer.borderColor = [UIColor whiteColor].CGColor;
    [nextStepBtn addTarget:self action:@selector(nextStepAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview: nextStepBtn];
    
    [nextStepBtn makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(btnsBgView.bottom).offset(100);
        make.width.equalTo(WGiveWidth(150.f));
        make.height.equalTo(WGiveHeight(50.f));
        make.centerX.equalTo(self.view.centerX);
    }];
    
    _selectTurnScrollView = [[UIScrollView alloc]init];
    _selectTurnScrollView.backgroundColor = [UIColor clearColor];
    _selectTurnScrollView.showsHorizontalScrollIndicator = NO;
    [self.view addSubview:_selectTurnScrollView];
    
    [_selectTurnScrollView makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(lineV.top).offset(5);
        make.left.right.equalTo(self.view);
        make.height.equalTo(WGiveHeight(60));
    }];
    
    
    _selectTurnBgView = [[UIView alloc]init];
    _selectTurnBgView.backgroundColor = [UIColor clearColor];
    [_selectTurnScrollView addSubview:_selectTurnBgView];
    
    [_selectTurnBgView makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(_selectTurnScrollView.centerY);
        make.centerX.equalTo(_selectTurnScrollView.centerX);
        make.height.equalTo(WGiveHeight(60));
    }];
    
    if (self.selectedSchedules.count > 0) {
        [self.navigationItem.rightBarButtonItem setEnabled:YES];
        CGFloat margin = 10;
        for (int i = 0 ; i < self.selectedSchedules.count; i++) {
            JWScheduleModel *model = [self.selectedSchedules objectAtIndex:i];
            // 添加
            UILabel *turnLabel = [[UILabel alloc]init];
            turnLabel.backgroundColor = model.scheduleColor;
            turnLabel.text = model.scheduleName;
            turnLabel.textColor = [UIColor whiteColor];
            turnLabel.font = [UIFont boldSystemFontOfSize:20.f];
            turnLabel.textAlignment = NSTextAlignmentCenter;
            turnLabel.layer.masksToBounds = YES;
            turnLabel.layer.cornerRadius = _selectTurnHeight/2.0;
            [turnLabel setAdjustsFontSizeToFitWidth:YES];
            [_selectTurnBgView addSubview:turnLabel];
            
            [turnLabel makeConstraints:^(MASConstraintMaker *make) {
                make.centerY.equalTo(_selectTurnBgView.centerY);
                make.height.equalTo(_selectTurnHeight);
                make.width.equalTo(_selectTurnHeight);
                make.left.equalTo(i * (margin + _selectTurnHeight));
            }];
        }
        
        _selectTurnScrollView.contentSize = CGSizeMake(self.selectedSchedules.count * (margin + _selectTurnHeight), WGiveHeight(60));

        [_selectTurnBgView updateConstraints:^(MASConstraintMaker *make) {
            make.width.equalTo(self.selectedSchedules.count * (margin + _selectTurnHeight));
        }];
    }else {
        [self.navigationItem.rightBarButtonItem setEnabled:NO];
    }
}

- (void)initalTitleView {
    
    _titleLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, 80, 80)];
    _titleLabel.backgroundColor = [UIColor clearColor];
    _titleLabel.textAlignment = NSTextAlignmentCenter;
    _titleLabel.font = [UIFont systemFontOfSize:CalendarTitleFont];
    _titleLabel.textColor = TitleColor;
    _titleLabel.text = self.isEdit ? @"编辑排班（2/3）" : @"创建排班（2/3）";
    
    self.navigationItem.titleView = _titleLabel;
    
}

#pragma mark - Action
- (void)btnBackGroundHighlighted:(UIButton *)btn {
    [btn setBackgroundColor:[UIColor lightGrayColor]];
}


/**
 添加倒班信息
 */
- (void)btnEventTouchUpInside:(UIButton *)btn {
    NSInteger i = btn.tag - TAG_BASE;
    JWScheduleModel *model = _allScheduleDatas[i];
    [btn setBackgroundColor: model.scheduleColor];
    
    if (self.selectedSchedules.count >= MAX_TURN_PERIOD) {
        // 限制选择倒班周期的个数
        [[NSString stringWithFormat:@"一个倒班周期数不能超过%d天哦~",MAX_TURN_PERIOD] show_alert_title:@"亲！对不起！"];
        return;
    }
    [self.selectedSchedules addObject:model];
    [self updateSelectTurnBgViewLayoutByAdd:YES];
    
    [self.navigationItem.rightBarButtonItem setEnabled:YES];
}

- (void)btnLong:(UILongPressGestureRecognizer *)gestureRecognizer{
    UIButton *btn = (UIButton *)[gestureRecognizer view];
    
    if ([gestureRecognizer state] == UIGestureRecognizerStateBegan) {
        NSInteger i = btn.tag - TAG_BASE;
        JWScheduleModel *model = _allScheduleDatas[i];
        [btn setBackgroundColor: model.scheduleColor];
        
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"修改班名" message:@"最多可以输入【3】个字来代替您的班名"delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"修改", nil];
        alertView.alertViewStyle = UIAlertViewStylePlainTextInput;//看这里。。可以这样用
        
        [alertView textFieldAtIndex:0].text = model.scheduleName;
        [alertView textFieldAtIndex:0].font = [UIFont boldSystemFontOfSize:40];
        [alertView textFieldAtIndex:0].textAlignment = NSTextAlignmentCenter;
        [[alertView textFieldAtIndex:0] addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
        alertView.tag = i + ALERT_VIEW_TAG_BASE;
        [alertView show];
    }
}

#pragma mark- UIAlertViewDelegate
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    
    if (buttonIndex == 1) {
        NSInteger i = alertView.tag - ALERT_VIEW_TAG_BASE;
        JWScheduleModel *model = _allScheduleDatas[i];
        UITextField *txtfield = [alertView textFieldAtIndex:0];
        model.scheduleName = txtfield.text;
        
        UIButton *btn = (UIButton *)[self.view viewWithTag:i + TAG_BASE];
        [btn setTitle:model.scheduleName forState:UIControlStateNormal];
        
    }
}

- (void)textFieldDidChange:(UITextField *)textField
{
    NSString *toBeString = textField.text;
    NSString *lang = [[UITextInputMode currentInputMode] primaryLanguage]; // 键盘输入模式
    if ([lang isEqualToString:@"zh-Hans"]) { // 简体中文输入，包括简体拼音，健体五笔，简体手写
        UITextRange *selectedRange = [textField markedTextRange];
        //获取高亮部分
        UITextPosition *position = [textField positionFromPosition:selectedRange.start offset:0];
        // 没有高亮选择的字，则对已输入的文字进行字数统计和限制
        if (!position) {
            if (toBeString.length > 3) {
                
                textField.text = [toBeString substringToIndex:3];
            }
        }
        // 有高亮选择的字符串，则暂不对文字进行统计和限制
        else {
            
        }
    }
    // 中文输入法以外的直接对其统计限制即可，不考虑其他语种情况
    else{
        if (toBeString.length > 3) {
            
            textField.text = [toBeString substringToIndex:3];
        }
    }
    
}

/**
 撤销
 */
- (void)backout:(id)btn {
    [self.selectedSchedules removeLastObject];
    [self updateSelectTurnBgViewLayoutByAdd:NO];
    
    if (self.selectedSchedules.count == 0) {
        [self.navigationItem.rightBarButtonItem setEnabled:NO];
    }

}

/**
 下一步
 */
- (void)nextStepAction:(UIButton *)btn {
    if (self.selectedSchedules.count == 0) {
        UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"" message:@"亲！请先设置您的倒班规律吧~" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alertView show];
        return;
    }
    
    SettingTurnLastStepViewController *vc = [[SettingTurnLastStepViewController alloc]initWithNibName:NSStringFromClass([SettingTurnLastStepViewController class]) bundle:nil];
    vc.currentSelectTurnDatas = self.selectedSchedules;
    vc.turnName = self.turnName;
    vc.isEdit = self.isEdit;
    if (self.calendarModel != nil) {
        vc.calendarModel = self.calendarModel;
    }
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)updateSelectTurnBgViewLayoutByAdd:(BOOL)isAdd {
    
    NSArray *subviews = [_selectTurnBgView subviews];
    CGFloat margin = 10;
    if (isAdd) {
        JWScheduleModel *model = [self.selectedSchedules lastObject];
        // 添加
        UILabel *turnLabel = [[UILabel alloc]init];
        turnLabel.backgroundColor = model.scheduleColor;
        turnLabel.text = model.scheduleName;
        turnLabel.textColor = [UIColor whiteColor];
        turnLabel.font = [UIFont boldSystemFontOfSize:20.f];
        turnLabel.textAlignment = NSTextAlignmentCenter;
        turnLabel.layer.masksToBounds = YES;
        turnLabel.layer.cornerRadius = _selectTurnHeight/2.0;
        [turnLabel setAdjustsFontSizeToFitWidth:YES];
        [_selectTurnBgView addSubview:turnLabel];
        
        if (subviews.count > 0) {
            [turnLabel makeConstraints:^(MASConstraintMaker *make) {
                make.centerY.equalTo(_selectTurnBgView.centerY);
                make.height.equalTo(_selectTurnHeight);
                make.width.equalTo(_selectTurnHeight);
                make.left.equalTo(((UIView *)subviews[subviews.count - 1]).right).offset(margin);
            }];
            
            [_selectTurnBgView updateConstraints:^(MASConstraintMaker *make) {
                make.width.equalTo((subviews.count + 1) * (margin + _selectTurnHeight));
            }];
            
            [UIView animateWithDuration:animationDurations animations:^{
                [self.view layoutIfNeeded];
            }];
        }else {
            [_selectTurnBgView updateConstraints:^(MASConstraintMaker *make) {
                make.width.equalTo(_selectTurnHeight);
            }];
            
            [turnLabel makeConstraints:^(MASConstraintMaker *make) {
                make.centerY.equalTo(_selectTurnBgView.centerY);
                make.height.equalTo(_selectTurnHeight);
                make.width.equalTo(_selectTurnHeight);
                make.left.equalTo(0);
            }];
            
        }
       
    }else {
        // 清除
        if (subviews.count > 0) {
            [[subviews lastObject] removeFromSuperview];
            
            [_selectTurnBgView updateConstraints:^(MASConstraintMaker *make) {
                make.width.equalTo((subviews.count - 1) * (margin + _selectTurnHeight));
            }];
            
            [UIView animateWithDuration:animationDurations animations:^{
                [self.view layoutIfNeeded];
            }];
        }
    }
    
    _selectTurnScrollView.contentSize = CGSizeMake(self.selectedSchedules.count * (margin + _selectTurnHeight), WGiveHeight(60));
    
    if (_selectTurnScrollView.contentSize.width > self.view.frame.size.width) {
        [_selectTurnScrollView setContentOffset:CGPointMake(_selectTurnScrollView.contentSize.width - self.view.frame.size.width, 0) animated:YES];
    }
    
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - getter
- (NSMutableArray *)selectedSchedules {
    if (!_selectedSchedules) {
        _selectedSchedules = [[NSMutableArray alloc]init];
        if (self.calendarModel != nil) {
            RLMArray *roundmodels = self.calendarModel.scheduleStatus;
            
            if (roundmodels != nil && roundmodels.count > 0) {
                for (JWScheduleModel *model in roundmodels) {
                    [_selectedSchedules addObject:model];
                }
                
            }
        }
    }
    return _selectedSchedules;
}

- (NSMutableArray *)allScheduleDatas {
    if (!_allScheduleDatas) {
        _allScheduleDatas = [[NSMutableArray alloc]init];
        RLMResults *localData = [[JWRealmManager defaultManager] queryAllSchedules];
        for (JWScheduleModel *schedule in localData) {
            [_allScheduleDatas addObject:schedule];
        }
    }
    return _allScheduleDatas;
}

@end
